package com.shou.zhnfyxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shou.zhnfyxt.entity.Error;
import com.shou.zhnfyxt.entity.LoginUser;
import com.shou.zhnfyxt.entity.R;
import com.shou.zhnfyxt.entity.User;
import com.shou.zhnfyxt.mapper.UserMapper;
import com.shou.zhnfyxt.service.LoginServcie;
import com.shou.zhnfyxt.service.UserService;
import com.shou.zhnfyxt.utils.JwtUtil;
import com.shou.zhnfyxt.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@Controller
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private LoginServcie loginServcie;


    @PostMapping("login")
    public R<Map<String, String>> userLogin(@RequestBody User user) {
        return loginServcie.login(user);
    }


//    @PostMapping("register")
//    public R<User> userRegister(@RequestBody User user) {
//        String username = user.getUsername();
//        String password = user.getPassword();
//        List<User> userList = userMapper.selectList(null);
//        List<String> collect = userList.stream().map(User::getUsername).collect(Collectors.toList());
//        for (String s : collect) {
//            if (username.equals(s)) {
//                return R.error(Error.USERNAMEDUPLICATE);
//            }
//        }
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
//        String email = user.getEmail();
//        Date nowDate = new Date();
//        Timestamp created = new Timestamp(nowDate.getTime());
//        Timestamp updated = new Timestamp(nowDate.getTime());
//        String id = UUID.randomUUID().toString();
//        int status = -1;
//        User newUser = new User(id,username, password, email, created, updated,status);
//        userService.save(newUser);
//        return R.success(newUser);
//    }

    @PostMapping("button")
    public R<User> userButton(@RequestBody String userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        User user = userMapper.selectOne(wrapper);
        user.setStatus(String.valueOf(0));
        boolean save = userService.updateById(user);
        if (save) {
            return R.success(user);
        } else {
            return R.error(111);
        }
    }

    @GetMapping("getUsernameByUserId")
    public R<String> getUsernameByUserId(@RequestHeader String token) {
        Claims claims = JwtUtil.parseJWT(token);
        String userId = claims.getSubject();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", userId);
        User user = userMapper.selectOne(userQueryWrapper);
        return R.success(user.getUsername());
    }

    @PostMapping("changePassword")
    public R<String> changePassword(@RequestBody Map<String, Object> params, @RequestHeader String token) {
        Claims claims = JwtUtil.parseJWT(token);
        String userId = claims.getSubject();
        String oldPassword = (String) params.get("oldpassword");
        String newPassword = (String) params.get("newpassword");
        String certainpassword = (String) params.get("certainpassword");



        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User user = userService.getOne(queryWrapper);
        String password = user.getPassword();


        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        if (passwordEncoder.matches(oldPassword,password)) {
            if (Objects.equals(newPassword, certainpassword)) {
                newPassword = passwordEncoder.encode(newPassword);
                user.setPassword(newPassword);
                userMapper.update(user, queryWrapper);
                return R.success(userId);
            }
            else {
                return R.error(Error.TWOPASSWORDISNOTMATCH);
            }
        }
        else {
            return R.error(Error.PASSWORDERROR);
        }
    }
    @PostMapping("test")
    public void test() {
        System.out.println("test");
    }

    @PostMapping("loginout")
    public R<Integer> loginout(@RequestHeader String token) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String id = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return  R.success(200);}

    @PostMapping("setNickName")
    public R<Integer> setNickName(@RequestBody String nickname, @RequestHeader String token){
        Claims claims = JwtUtil.parseJWT(token);
        String userId = claims.getSubject();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        User user = userService.getOne(queryWrapper);
        user.setNickname(nickname);
        userService.update(user, queryWrapper);
        return R.success(200);
    }

    @GetMapping("getNickName")
    public R<String> getNickName(@RequestHeader String token) {
        Claims claims = JwtUtil.parseJWT(token);
        String userId = claims.getSubject();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", userId);
        User user = userMapper.selectOne(userQueryWrapper);
        return R.success(user.getNickname());
    }

}
